﻿<%@ WebHandler Language="C#" Class="ZSLimitedCapacityHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;

/// <summary>
/// add by longb 2022-08-30
/// 装试排产-----一般处理程序
/// </summary>
public class ZSLimitedCapacityHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;    
    ZSLimitedCapacityBusiness m_ZsLimitCB = new ZSLimitedCapacityBusiness();
    FullStatisticsAnalysisBusiness m_fullab = new FullStatisticsAnalysisBusiness();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "GetZsApsOrderTask": //获取装试排产任务单
                    GetZsApsOrderTask(context);
                    break;
                case "AddOrderToApsPool"://添加装试排产任务单到--排产池
                    AddOrderToApsPool(context);
                    break;
                case "removeApsPool"://装试排产池--移除--任务单
                    removeApsPool(context);
                    break;
                case "apsLmCalculate"://装试Aps排产
                    apsLmCalculate(context);
                    break;
                case "getContainerLMAps"://
                    GetContainerLMAps(context);
                    break;
                case "getStepApsResult"://装试排产--甘特图查看
                    GetStepApsResult(context);
                    break;    
                case "GetZsApsPlanInfoBymfgOrder"://根据订单号--查询--已排产的任务单--(排产结果页面使用)
                    GetZsApsPlanInfoBymfgOrder(context);
                    break;
                case "getStepInfiniteAps"://查询工序排产结果--(排产结果页面使用)
                    getStepInfiniteAps(context);
                    break;
                case "adjustInfiniteAps"://调整排产结果--(排产结果页面使用)
                    AdjustInfiniteAps(context);
                    break;
                case "confirmAdjustedResult"://调整排产结果[确认]--(排产结果页面使用)
                    ConfirmAdjustedResult(context);
                    break;
                case "examineAndconfirmApsResult"://排产结果审核确认
                    ExamineAndconfirmApsResult(context);
                    break;
                case "GetWorkStationApsForGrant"://工位甘特图
                    GetWorkStationApsForGrant(context);
                    break;   
                case "getStepInfiniteAps2":
                    getStepInfiniteAps2(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    /// <summary>
    /// 装试排产--查询--待加入排产池任务单
    /// </summary>
    /// <param name="context"></param>
    private void GetZsApsOrderTask(HttpContext context)
    {
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var para=new Dictionary<string,string>();
        para.Add("CurrentPageIndex", pageNumber);
        para.Add("PageSize", pageSize);
        if (dt.Columns.Contains("ContainerNo"))
        {
            para.Add("ContainerNo", dt.Rows[0]["ContainerNo"].ToString());
        }
        if (dt.Columns.Contains("Machine"))
        {
            para.Add("Machine", dt.Rows[0]["Machine"].ToString());
        }
        if (dt.Columns.Contains("MfgOrdername"))
        {
            para.Add("MfgOrdername", dt.Rows[0]["MfgOrdername"].ToString());
        }
        if (dt.Columns.Contains("WorkFlowType"))
        {
            para.Add("WorkFlowType", dt.Rows[0]["WorkFlowType"].ToString());
        }
        if (dt.Columns.Contains("HasBom"))
        {
            para.Add("HasBom", dt.Rows[0]["HasBom"].ToString());
        }

        //yuxj2023-4-1增加日期查询
        if (dt.Columns.Contains("PlanStartTime"))
        {
            para.Add("PlanStartTime", dt.Rows[0]["PlanStartTime"].ToString());
        }
        if (dt.Columns.Contains("PlanEndTime"))
        {
            para.Add("PlanEndTime", dt.Rows[0]["PlanEndTime"].ToString());
        }
        
        para.Add("FactoryID", m_UserInfo.FactoryID.ToString());
        para.Add("IsPool", context.Request["IsPool"].ToString());
        uMESProcessResult result = m_ZsLimitCB.GetZsApsOrderTask(para);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 添加装试排产任务单到--排产池
    /// </summary>
    /// <param name="context"></param>
    private void AddOrderToApsPool(HttpContext context)
    {
        var containers = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        m_ZsLimitCB.MoveContainerToAps(containers);
        uMESProcessResult result =new uMESProcessResult();
        result.Result = true;
        result.Message = "添加成功";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 装试排产任务单--移出--排产池
    /// </summary>
    /// <param name="context"></param>
    private void removeApsPool(HttpContext context)
    {
        var containers = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        m_ZsLimitCB.RemoveApsPool(containers);
        uMESProcessResult result = new uMESProcessResult();
        result.Result = true;
        result.Message = "移除成功";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 装试Aps排产
    /// </summary>
    private void apsLmCalculate(HttpContext context) 
    {
        uMESProcessResult result = new uMESProcessResult();
        m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
        Dictionary<string, string> para = new Dictionary<string, string>();
        para["EmployeeID"] = m_UserInfo.EmployeeID.ToString();
        para["FactoryID"] = m_UserInfo.FactoryID.ToString();
        var containers = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());//任务单信息
        var policy1 = context.Request["policy1"].ToString();//Ⅰ级排产策略（0：订单优先级，1：齐套)
        var policy2 = context.Request["policy2"].ToString();//Ⅱ级排产策略（2：工序齐套，3：瓶颈工序）
        var policy3 = context.Request["policy3"].ToString();//Ⅲ级排产策略（4：计划完成时间，5：计划开始时间）
        var policy4 = context.Request["policy4"].ToString();//Ⅳ级排产策略（6：负载均衡，7：空闲时间优先）

        DataTable dtPolicy = new DataTable();
        dtPolicy.Columns.Add("policy1");
        dtPolicy.Columns.Add("policy2");
        dtPolicy.Columns.Add("policy3");
        dtPolicy.Columns.Add("policy4");
        DataRow dr = dtPolicy.NewRow();
        dr["policy1"] = policy1;
        dr["policy2"] = policy2;
        dr["policy3"] = policy3;
        dr["policy4"] = policy4;
        dtPolicy.Rows.Add(dr);

        if (policy1 == "0")//订单优先级--升序排序
        {
            containers.DefaultView.Sort = "PLANNEDFINISHDATE, PRIO DESC";//PLANNEDFINISHDATE完成时间优先
            containers = containers.DefaultView.ToTable();
        }
        else//齐套策略---订单齐套验证
        {
            var ContainerNo = CheckContainerFullset(containers);
            if (!string.IsNullOrWhiteSpace(ContainerNo)) {
                result.Message = "齐套策略--任务单【" + ContainerNo + "】未齐套";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
        }

        result = m_ZsLimitCB.ZSAPSCalculate(containers, dtPolicy, para);
        //result.Result = result.DBTable.Rows.Count > 0;
        result.Message = result.Result ? "排产成功" : "排产失败：" + result.Message;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    
    
    
    /// <summary>
    /// 检查--任务单是否齐套
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    private string CheckContainerFullset(DataTable dt) {
        var ContainerNo = string.Empty;
        foreach(DataRow row in dt.Rows){
            var para = new Dictionary<string, string>();
            para.Add("ContainerNo", row["containerNo"].ToString());//任务单号
            para.Add("ContainerID", row["containerid"].ToString());
            para.Add("workflowid", row["workflowid"].ToString());
            para.Add("mfgorderid", row["mfgorderid"].ToString());
            DataTable dtt = m_fullab.GetSpec(para);
            DataView spec = dtt.DefaultView;
            spec.RowFilter = "(PCOUNT<>0 AND (PCOUNT=CCOUNT))";//查询工序下有大小件信息（去封/集件报工==需求）条数
            DataTable dtl = spec.ToTable();

            DataView Aspec = dtt.DefaultView;
            Aspec.RowFilter = "PCOUNT<>0";
            DataTable dtll = Aspec.ToTable();
            if (dtl.Rows.Count!=dtll.Rows.Count) {
                ContainerNo += row["containerNo"].ToString()+",";
            }
        }
        return ContainerNo;
    }

    public void GetContainerLMAps(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        Dictionary<string, string> para = new Dictionary<string, string>();
        para["EmployeeID"] = m_UserInfo.EmployeeID.ToString();

        DataTable conDt = new DataTable();
        if (!string.IsNullOrWhiteSpace(context.Request.Form["containers"].ToString()))
        {
            conDt = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["containers"].ToString());
        }
        else
        {
            result.Message = "无效参数";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (context.Request["apsType"] != null && !string.IsNullOrWhiteSpace(context.Request["apsType"].ToString()))
        {
            para["ApsType"] = context.Request["apsType"].ToString();
        }

        DataTable dt = m_ZsLimitCB.GetContainerLMAps(conDt, para);
        result.DBTable = dt;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 排产甘特图--查看
    /// </summary>
    /// <param name="context"></param>
    private void GetStepApsResult(HttpContext context) {
        uMESProcessResult result = new uMESProcessResult();
        var para = new Dictionary<string, string>();
        para.Add("ContainerID", context.Request["param"].ToString());
        if(context.Request["isCompare"].ToString()=="false"){
        para.Add("apsType",context.Request["apsType"].ToString());
        }
        DataTable dt = m_ZsLimitCB.GetStepInfiniteAps(para);

        if (dt.Rows.Count == 0)
        {
            result.Message = "无数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }

        Dictionary<string, object> apsData = new Dictionary<string, object>();
        List<Dictionary<string, object>> returnData = new List<Dictionary<string, object>>();

        DataTable conDt = dt.DefaultView.ToTable(true, "containerid", "workflowid");//批次 

        foreach (DataRow con in conDt.Rows)
        {
            var conStepApsInfo = dt.Select("containerid='" + con["containerid"].ToString() + "' and workflowid='" + con["workflowid"].ToString() + "'").CopyToDataTable();
            var conApsInfo = conStepApsInfo.DefaultView.ToTable(true, "apsplaninfoid", "constarttime", "conendtime", "containername", "ApsType", "containerid", "workflowid");//批次级计划
            var conApsRow = conApsInfo.Rows[0];

            apsData = new Dictionary<string, object>();
            apsData["id"] = conApsRow["containerid"].ToString();
            apsData["name"] = conApsRow["containername"].ToString();

            List<Dictionary<string, object>> conperiods = new List<Dictionary<string, object>>();
            Dictionary<string, object> conPeriod = new Dictionary<string, object>();
            Dictionary<string, object> customData = new Dictionary<string, object>();
            //批次级计划，可能3种方案
            foreach (DataRow _conApsRow in conApsInfo.Rows)
            {
                conPeriod = new Dictionary<string, object>();
                var apsType = ""; var fillColor = "";
                switch (_conApsRow["ApsType"].ToString().Contains("5")?"1":"2")
                {
                    case "1":
                        apsType = "正排";
                        fillColor = "#64b5f6";
                        break;
                    case "2":
                        apsType = "倒排";
                        fillColor = "#009688";
                        break;
                    case "3":
                        apsType = "瓶颈排";
                        fillColor = "#9d8a0e";
                        break;
                    default:
                        break;
                }
                conPeriod["id"] = _conApsRow["apsplaninfoid"].ToString();
                conPeriod["text"] = _conApsRow["containername"].ToString() + "(" + apsType + ")";
                conPeriod["start"] = _conApsRow["constarttime"].ToString();
                conPeriod["end"] = _conApsRow["conendtime"].ToString();
                conPeriod["fill"] = fillColor;

                //个性化属性
                customData = new Dictionary<string, object>();
                customData["apsType"] = _conApsRow["ApsType"].ToString();

                conPeriod["customData"] = customData;

                conperiods.Add(conPeriod);
            }
            apsData["periods"] = conperiods;

            //批次级个性化属性
            customData = new Dictionary<string, object>();
            customData["containerid"] = con["containerid"].ToString();
            customData["workflowid"] = con["workflowid"].ToString();

            apsData["customData"] = customData;

            returnData.Add(apsData);

            //工序级信息
            DataTable conStep = conStepApsInfo.DefaultView.ToTable(true, "containerid", "workflowid", "workflowstepid", "workflowstepname");//工序信息                      

            foreach (DataRow step in conStep.Rows)
            {
                Dictionary<string, object> stepApsData = new Dictionary<string, object>();

                stepApsData["id"] = step["workflowstepid"].ToString();
                stepApsData["name"] = step["workflowstepname"].ToString();
                List<Dictionary<string, object>> periods = new List<Dictionary<string, object>>();
                Dictionary<string, object> period = new Dictionary<string, object>();

                //此批次和此工序的所有排产计划
                DataTable _conStepApsInfo = conStepApsInfo.Select("containerid='" + con["containerid"].ToString() + "' and workflowstepid='" + step["workflowstepid"].ToString() + "'").CopyToDataTable();
                foreach (DataRow stepAps in _conStepApsInfo.Rows)
                {
                    period = new Dictionary<string, object>();
                    var apsType = ""; var fillColor = "";
                    switch (stepAps["ApsType"].ToString().Contains("5") ? "1" : "2")
                    {
                        case "1":
                            apsType = "正排";
                            fillColor = "#64b5f6";
                            break;
                        case "2":
                            apsType = "倒排";
                            fillColor = "#009688";
                            break;
                        case "3":
                            apsType = "瓶颈排";
                            fillColor = "#9d8a0e";
                            break;
                        default:
                            break;
                    }
                    period["id"] = stepAps["apsplandetailid"].ToString();
                    period["text"] = stepAps["workflowstepname"].ToString() + "(" + apsType + ")";
                    period["start"] = stepAps["stepstarttime"].ToString();
                    period["end"] = stepAps["stependtime"].ToString();
                    period["showcolor"] = stepAps["showcolor"].ToString(); //yuxj增加颜色标识20230420
                    period["workstation"] = stepAps["workstationname"].ToString();//增加工位显示                    
                    
                    period["fill"] = fillColor;
                    //个性化属性
                    customData = new Dictionary<string, object>();
                    customData["apsType"] = stepAps["ApsType"].ToString();

                    period["customData"] = customData;

                    periods.Add(period);
                }
                stepApsData["periods"] = periods;
                stepApsData["parent"] = conApsRow["containerid"].ToString();
                returnData.Add(stepApsData);
            }

        }

        result.ReturnData = JsonConvert.SerializeObject(returnData);
        //result.DBTable = dt;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    
    /// <summary>
    /// 根据订单号--查询--已排产的任务单
    /// </summary>
    /// <param name="context"></param>
    private void GetZsApsPlanInfoBymfgOrder(HttpContext context) 
    {
        var mfgorderName = context.Request["mfgorderName"].ToString();
        var para=new Dictionary<string,string>();
        para.Add("MfgOrdername", mfgorderName);
        para.Add("FactoryID", m_UserInfo.FactoryID.ToString());
        para.Add("status", context.Request["status"].ToString());
        uMESProcessResult result = new uMESProcessResult();
        result.DBTable = m_ZsLimitCB.GetZsApsPlanInfoBymfgOrder(para);
        result.Result = result.DBTable.Rows.Count > 0;
        result.Message = result.Result ? "" : "根据订单号没有查询到已排产的任务单信息";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    private void getStepInfiniteAps(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        Dictionary<string, string> para = new Dictionary<string, string>();
        //para.Add("ApsPlanInfoIDs", context.Request["param"].ToString());
        //para.Add("mfgorderName", context.Request["mfgorderName"].ToString());
        para.Add("status", context.Request["status"].ToString());
        //if ((context.Request["param"] != null) && (!String.IsNullOrWhiteSpace(context.Request["param"].ToString())))
        //{
        //    para.Add("ApsPlanInfoIDs", context.Request["param"].ToString());
        //}

        if ((context.Request["machine"] != null) && (!String.IsNullOrWhiteSpace(context.Request["machine"].ToString())))
        {
            para.Add("Machine", context.Request["machine"].ToString());
        }
        if ((context.Request["containerNo"] != null) && (!String.IsNullOrWhiteSpace(context.Request["containerNo"].ToString())))
        {
            para.Add("ContainerNo", context.Request["containerNo"].ToString());
        }
        if ((context.Request["mfgorderName"] != null) && (!String.IsNullOrWhiteSpace(context.Request["mfgorderName"].ToString())))
        {
            para.Add("MfgorderName", context.Request["mfgorderName"].ToString());
        }
        if ((context.Request["planStartTime"] != null) && (!String.IsNullOrWhiteSpace(context.Request["planStartTime"].ToString())))
        {
            para.Add("PlanStartTime", context.Request["planStartTime"].ToString());
        }

        if ((context.Request["planEndTime"] != null) && (!String.IsNullOrWhiteSpace(context.Request["planEndTime"].ToString())))
        {
            para.Add("PlanEndTime", context.Request["planEndTime"].ToString());
        }
                
        //if (String.IsNullOrWhiteSpace(context.Request["param"].ToString()) && String.IsNullOrWhiteSpace(context.Request["mfgorderName"].ToString()))
        //{
        //    result.Message = "请输入查询条件";
        //    context.Response.Write(JsonConvert.SerializeObject(result));
        //    return;
        //}

        if (para.Count < 2)
        {
            result.Message = "请输入查询条件";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }

        DataTable dt = m_ZsLimitCB.GetStepInfiniteAps(para);

        if (dt.Rows.Count == 0)
        {
            result.Message = "无数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }

        Dictionary<string, object> apsData = new Dictionary<string, object>();
        List<Dictionary<string, object>> returnData = new List<Dictionary<string, object>>();

        DataTable conDt = dt.DefaultView.ToTable(true, "apsplaninfoid", "constarttime", "conendtime", "containername", "ApsType", "containerid", "workflowid","workflowtype");//批次级计划
        conDt.DefaultView.Sort = "containerid,containername";//add by longb 2023-11-14
        conDt = conDt.DefaultView.ToTable();//add by longb 2023-11-14
        if (!conDt.Columns.Contains("isCheck")) { conDt.Columns.Add("isCheck"); }
        result.DBTable = conDt;
        foreach (DataRow con in conDt.Rows)
        {
            apsData = new Dictionary<string, object>();
            apsData["id"] = con["apsplaninfoid"].ToString();
            apsData["name"] = con["containername"].ToString() + (con["ApsType"].ToString().Contains("5") ? "(正排)" : "(倒排)");
            apsData["containerid"] = con["containerid"].ToString();//add by longb 2023-11-14
            apsData["collapsed"] =context.Request["status"].ToString()=="0"?false: true;
            List<Dictionary<string, object>> conperiods = new List<Dictionary<string, object>>();
            Dictionary<string, object> conPeriod = new Dictionary<string, object>();
            var conStart = con["constarttime"].ToString();//uLMS_CommonFunction.GetMsStamp(DateTime.Parse(con["constarttime"].ToString()));
            var conEnd = con["conendtime"].ToString();// uLMS_CommonFunction.GetMsStamp(DateTime.Parse(con["conendtime"].ToString())); 
            conPeriod["id"] = Guid.NewGuid().ToString();

            conPeriod["text"] = con["containername"].ToString();
            conPeriod["start"] = conStart;
            conPeriod["end"] = conEnd;
            conPeriod["fill"] = "#5FB878";

            conperiods.Add(conPeriod);

            apsData["periods"] = conperiods;
            //批次级个性化属性
            Dictionary<string, object> conCustomData = new Dictionary<string, object>();
            conCustomData["differ"] = 0;//调整的差值
            conCustomData["constarttime"] = conStart;
            conCustomData["conendtime"] = conEnd;
            conCustomData["apsType"] = con["apsType"].ToString();
            conCustomData["containerid"] = con["containerid"].ToString();
            conCustomData["workflowid"] = con["workflowid"].ToString();

            apsData["customData"] = conCustomData;

            returnData.Add(apsData);

            //工序级信息
            DataRow[] steps = dt.Select("apsplaninfoid='" + con["apsplaninfoid"].ToString() + "'");
            var number = 0;
            foreach (DataRow stepAps in steps)
            {
                Dictionary<string, object> stepApsData = new Dictionary<string, object>();

                stepApsData["id"] = stepAps["apsplandetailid"].ToString();
                stepApsData["name"] = stepAps["workflowstepname"].ToString();
                stepApsData["number"] = number;//add by longb 2023-11-13 工序顺序号
                stepApsData["differ"] = 0;//add by longb 2023-11-13 调整的差值
                number++;
                List<Dictionary<string, object>> periods = new List<Dictionary<string, object>>();
                Dictionary<string, object> period = new Dictionary<string, object>();
                period["id"] = Guid.NewGuid().ToString();
                period["text"] = stepAps["workflowstepname"].ToString();
                period["start"] = stepAps["stepstarttime"].ToString();// uLMS_CommonFunction.GetMsStamp(DateTime.Parse(stepAps["stepstarttime"].ToString()));
                period["end"] = stepAps["stependtime"].ToString();//uLMS_CommonFunction.GetMsStamp(DateTime.Parse(stepAps["stependtime"].ToString())); 
                period["showcolor"] = stepAps["showcolor"].ToString(); //yuxj增加颜色标识20230420
                period["workstation"] = stepAps["workstationname"].ToString();//增加工位显示 
               
                periods.Add(period);
                stepApsData["periods"] = periods;
                stepApsData["parent"] = con["apsplaninfoid"].ToString();
                returnData.Add(stepApsData);
            }

        }
        result.ReturnData = JsonConvert.SerializeObject(returnData);
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 调整排产结果-总体好像没用，先屏蔽 yuxj2023-4-1
    /// </summary>
    /// <param name="context"></param>
    public void AdjustInfiniteAps(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        if (!string.IsNullOrWhiteSpace(context.Request["conAps"].ToString()))
        {
            var conAps = JsonConvert.DeserializeObject<DataTable>(context.Request["conAps"].ToString());
            if (conAps.Rows.Count == 0)
            {
                result.Message = "无参数";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
            //Dictionary<string, string> para = new Dictionary<string, string>();
            //para["MakeCalendarID"] = "123";
            //para["EmployeeID"] = m_UserInfo.EmployeeID.ToString();

            //m_ZsLimitCB.AdjustInfiniteCalculate(conAps, para);
            var list = new ArrayList();
            foreach (DataRow row in conAps.Rows) 
            {
                if (row["type"].ToString().Equals("c")) {
                    list.Add(string.Format("update APSPLANINFO set STARTTIME =to_date('{0}','yyyy-MM-dd hh24:mi:ss'),ENDTIME=to_date('{1}','yyyy-MM-dd hh24:mi:ss') where APSPLANINFOID='{2}' ", row["STARTTIME"], row["ENDTIME"], row["apsPlanInfoID"]));
                }
                if (row["type"].ToString().Equals("s")) {
                    list.Add(string.Format("update ApsPlanDetail set STARTTIME =to_date('{0}','yyyy-MM-dd hh24:mi:ss'),ENDTIME=to_date('{1}','yyyy-MM-dd hh24:mi:ss') where APSPLANDETAILID='{2}' ", row["STARTTIME"], row["ENDTIME"], row["apsPlanInfoID"]));
                }
            }

           result.Result= DatabaseHelper.ExecuteSqlListTran(list);
            
        }
        else
        {
            result.Message = "无参数";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 调整排产结果[确认/退回]
    /// </summary>
    private void ConfirmAdjustedResult(HttpContext context) 
    {
        var containers = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var status = context.Request["status"].ToString();
        uMESProcessResult result = new uMESProcessResult();
        result.Result = m_ZsLimitCB.UpdateApsPlanStatus(m_UserInfo.EmployeeID.ToString(), containers, status);
        result.Message = result.Result ? "确认成功" : "确认失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 排产结果审核确认
    /// </summary>
    /// <param name="context"></param>
    private void ExamineAndconfirmApsResult(HttpContext context) 
    {
        var containers = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        uMESProcessResult result = new uMESProcessResult();
        result = m_ZsLimitCB.ConfirmApsPlanStatus(m_UserInfo.EmployeeID.ToString(), containers);
        result.Message = result.Result ? "确认成功" :"确认失败:"+ result.Message;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 工位甘特图
    /// </summary>
    /// <param name="context"></param>
    private void GetWorkStationApsForGrant(HttpContext context) 
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        Dictionary<string, string> para = new Dictionary<string, string>();

        if (context.Request["factoryID"] != null && !string.IsNullOrWhiteSpace(context.Request["factoryID"].ToString()))
        {
            para.Add("FactoryID", context.Request["factoryID"].ToString());
        }
        if (context.Request["workcenterID"] != null && !string.IsNullOrWhiteSpace(context.Request["workcenterID"].ToString()))
        {
            para.Add("WorkcenterID", context.Request["workcenterID"].ToString());
        }
        if (context.Request["shiftID"] != null && !string.IsNullOrWhiteSpace(context.Request["shiftID"].ToString()))
        {
            para.Add("ShiftID", context.Request["shiftID"].ToString());
        }
        if (context.Request["startDate"] != null && !string.IsNullOrWhiteSpace(context.Request["startDate"].ToString()))
        {
            para.Add("StartDate", context.Request["startDate"].ToString());
        }
        if (context.Request["endDate"] != null && !string.IsNullOrWhiteSpace(context.Request["endDate"].ToString()))
        {
            para.Add("EndDate", context.Request["endDate"].ToString());
        }

        para.Add("Status", "2,1");
        DataTable dt = m_ZsLimitCB.GetEmpApsDataForGrant(para);

        //排产数据格式化
        List<Dictionary<string, object>> returnData = new List<Dictionary<string, object>>();
        DataTable resDt = dt.DefaultView.ToTable(true, "resourceid", "resname");        
        //yuxj20230421增加颜色标识
        resDt.Columns.Add("showcolor");
        foreach (DataRow dr in resDt.Rows)
        {
            var _resAps = dt.Select("resourceid='" + dr["resourceid"].ToString() + "' and showcolor='2'");
            if (_resAps.Length > 0)
                dr["showcolor"] = "2";//黄色

            _resAps = dt.Select("resourceid='" + dr["resourceid"].ToString() + "' and showcolor='1'");
            if (_resAps.Length > 0)
                dr["showcolor"] = "1";//红色
        }

        foreach (DataRow resRow in resDt.Rows)
        {
            Dictionary<string, object> resApsData = new Dictionary<string, object>();
            resApsData.Add("id", resRow["resourceid"].ToString());
            resApsData.Add("name", resRow["resname"].ToString());
            //resApsData.Add("rowHeight", 30);

            var _resAps = dt.Select("resourceid='" + resRow["resourceid"].ToString() + "'");

            List<Dictionary<string, object>> periods = new List<Dictionary<string, object>>();
            Dictionary<string, object> period = new Dictionary<string, object>();

            List<string> colorList = new List<string>() { "#DC143C", "#FFFF00", "#0000FF" };
            int lastColorIndex = 0; string lastApsplandetailiId = _resAps[0]["apsplandetailid"].ToString();
            var i = 0;
            var j = 0;
            foreach (DataRow resAps in _resAps)
            {
                period = new Dictionary<string, object>();

                if (lastApsplandetailiId != resAps["apsplandetailid"].ToString())
                {
                    lastApsplandetailiId = resAps["apsplandetailid"].ToString();
                    lastColorIndex++;
                    j++;
                    if (lastColorIndex > colorList.Count - 1)
                    {
                        lastColorIndex = 0;
                    }
                }
                var stepstart = resAps["stepstart"].ToString();
                period["id"] = Guid.NewGuid().ToString();
                period["text"] = "";
                period["start"] = resAps["stepstart"].ToString();
                period["end"] = resAps["stepend"].ToString();
                period["showcolor"] = resAps["showcolor"].ToString();//颜色标识 
                period["fill"] = colorList[lastColorIndex];

                //个性化属性
                var customData = new Dictionary<string, object>();
                customData["stepstarthms"] = resAps["stepstarthms"].ToString();
                customData["stependhms"] = resAps["stependhms"].ToString();
                var ratio = (DateTime.Parse(resAps["stependhms"].ToString()) - DateTime.Parse(resAps["stepstarthms"].ToString())).TotalMinutes;
                customData["ratio"] = 0.2; //Math.Round((ratio / (24 * 60)), 2);//高度占用比
                ratio = (DateTime.Parse(resAps["stepstarthms"].ToString()) - DateTime.Parse(resAps["stepstarthms"].ToString()).Date).TotalMinutes;
                customData["startPercent"] = j*Math.Round((ratio / (24 * 60)), 2);//起始位置比
                customData["containername"] = resAps["containername"].ToString();
                customData["workflowstepname"] = resAps["workflowstepname"].ToString();
                customData["resourceid"] = resAps["resourceid"].ToString();
                period["customData"] = customData;

                periods.Add(period);
                i++;
            }

            resApsData["periods"] = periods;

            returnData.Add(resApsData);
        }

        result.ReturnData = JsonConvert.SerializeObject(returnData);
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private void getStepInfiniteAps2(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        var strSql = @"select ai.ApsType,ai.apsplaninfoid ""id"",ai.apsplaninfoid,ai.containerid,
                       ep.CONTAINERNO     CONTAINERNAME,
                       to_char(ai.starttime,'yyyy-MM-dd hh24:mi:ss')        PLANSTART,
                       to_char(ai.endtime,'yyyy-MM-dd hh24:mi:ss')          PLANEND,
                       null workstationname,(select COUNT(1) from ApsPlanDetail ad where ad.apsplaninfoid = ai.apsplaninfoid) CN,
                        '#5FB878' ""color"",'closed' ""state""
                  from ApsPlanInfo ai
                  inner join enginepartplan ep on nvl(nvl(ep.CONTAINERID,ep.concontainerid),ep.ENGINECONTAINERID) = ai.containerid
                  where 1=1";
        var strSql2 = @"select ai.ApsType,ai.apsplaninfoid ""_parentId"",ai.apsplaninfoid , ad.apsplandetailid ""id"",
                       ad.workflowstepname     CONTAINERNAME,
                       to_char(ad.starttime,'yyyy-MM-dd hh24:mi:ss')        PLANSTART,
                       to_char(ad.endtime,'yyyy-MM-dd hh24:mi:ss')          PLANEND,
                       ws.workstationname,'#64b5f6' ""color""
                  from ApsPlanInfo ai
                  inner join enginepartplan ep on nvl(nvl(ep.CONTAINERID,ep.concontainerid),ep.ENGINECONTAINERID) = ai.containerid
                  left join ApsPlanDetail ad on ad.apsplaninfoid = ai.apsplaninfoid
                  left join workstation ws on ws.workstationid = ad.workstationid 
                  where ad.isuse = 0";
        var strWhere=string.Empty;
        if (!string.IsNullOrWhiteSpace(context.Request["mfgorderName"].ToString()))
        {
            strWhere += String.Format(" and ep.mfgorderName like '%{0}%' ", context.Request["mfgorderName"].ToString());
        }

        if (!string.IsNullOrWhiteSpace(context.Request["containerNo"].ToString()))
        {
            strWhere += String.Format(" and ep.ContainerNo like '%{0}%' ", context.Request["containerNo"].ToString());
        }

        if (string.IsNullOrWhiteSpace(context.Request["machine"].ToString()))
        {
            strWhere += String.Format(" and ep.machineno like '%{0}%' ", context.Request["machine"].ToString());
        }
        if (!String.IsNullOrWhiteSpace(context.Request["planStartTime"].ToString()))
        {
            strWhere += String.Format(" and ai.starttime>=to_date('{0}','yyyy/mm/dd') ", context.Request["planStartTime"].ToString()); 
        }
        if(!String.IsNullOrWhiteSpace(context.Request["planEndTime"].ToString())) {
                strWhere += String.Format(" and ai.endtime <=to_date('{0}','yyyy/mm/dd')+1 ", context.Request["planEndTime"].ToString());
        }
        strWhere += "and nvl(ai.status,0)='2'  order by ai.starttime,ai.containerid,ai.workflowid ";

        DataTable dt = DatabaseHelper.Query_ReturnDatTable(strSql+strWhere);
        DataTable dt1 = DatabaseHelper.Query_ReturnDatTable(strSql2 + strWhere + ",ad.workflowstepid");
        dt.Merge(dt1);

        var startdate = dt.Compute("MIN(PLANSTART)","");
        var enddate = dt.Compute("MAX(PLANEND)", "");
         Dictionary<string, object> date = new Dictionary<string, object>();
        date.Add("startdate",string.IsNullOrWhiteSpace(startdate.ToString())?"":Convert.ToDateTime(startdate).ToString("yyyy-MM-dd"));
        date.Add("enddate", string.IsNullOrWhiteSpace(enddate.ToString()) ? "" : Convert.ToDateTime(enddate).ToString("yyyy-MM-dd"));
        Dictionary<string, object> para = new Dictionary<string, object>();
        para.Add("total",dt.Rows.Count);
        para.Add("rows", dt);
        para.Add("dateRange", date);
        result.ReturnData = para;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    } 
    
    
}